package com.dz.generator.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author 梁建军
 * 创建日期： 2019/9/3
 * 创建时间： 19:56
 * @version 1.0
 * @since 1.0
 */
public class ZipUtil {
    private static final Logger log = LoggerFactory.getLogger(ZipUtil.class);

    private ZipUtil() {
    }

    /**
     * 创建ZIP文件
     *
     * @param sourcePath   文件或文件夹路径
     * @param outputStream 输出流
     */
    public static void createZip(File sourcePath, OutputStream outputStream) throws Exception {
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(outputStream);
            for (File file : sourcePath.listFiles()) {
                writeZip(file, "", zos);
            }
        } finally {
            try {
                if (zos != null) {
                    zos.close();
                }
            } catch (IOException e) {
            }

        }
    }

    private static void writeZip(File file, String parentPath, ZipOutputStream zos) throws Exception {
        if (file.exists()) {
            if (file.isDirectory()) {//处理文件夹
                parentPath += file.getName() + File.separator;
                File[] files = file.listFiles();
                if (files.length != 0) {
                    for (File f : files) {
                        writeZip(f, parentPath, zos);
                    }
                } else {
                    try {
                        zos.putNextEntry(new ZipEntry(parentPath));
                    } catch (IOException e) {
                        throw e;
                    }
                }
            } else {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(file);
                    ZipEntry ze = new ZipEntry(parentPath + file.getName());
                    zos.putNextEntry(ze);
                    byte[] content = new byte[1024];
                    int len;
                    while ((len = fis.read(content)) != -1) {
                        zos.write(content, 0, len);
                        zos.flush();
                    }

                } catch (Exception e) {
                    log.error("创建ZIP文件失败", e);
                    throw e;
                } finally {
                    try {
                        if (fis != null) {
                            fis.close();
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
}
